<?php
namespace app\index\home;
use app\common\controller\Common;
use think\Db; 
use app\common\controller\Jssdk; 

class User extends Common
{
    /**
     * 判断是否登录 
     */
    public function isLogin(){
        if(!session('index_daili.id')){
            $this->error('请先登录！',url('/index/index/index'));
        } 
    }
    
    public function index()
    {
        $this->isLogin(); 
        $daili_id = session('index_daili.id');
        $daili_info = Db::name('daili')->where("id = '{$daili_id}'")->find();
        $this->assign("daili_info",$daili_info);
        return $this->fetch();
    }
    
    /**
     * 代理授权
     */
    public function agentList(){
        $this->isLogin();
        $daili_id = session('index_daili.id');
        $daili_info = Db::name('daili')->where("sqh != '' and id = '{$daili_id}'")->find();
        $daili_info['dailijb'] = Db::name('dldj')->where("id = '{$daili_info['lddj_id']}'")->value('levelname');
        $this->assign("daili_info",$daili_info);
        return $this->fetch();
    }
    
    /**
     * 查看授权
     */
    public function chakanShouquan(){
        $this->isLogin();
        $daili_id = session('index_daili.id');
        $daili_info = Db::name('daili')->where("sqh != '' and id = '{$daili_id}'")->find();  
        if($daili_info['sqs_path'] == ''){ 
            $root_dir = $_SERVER['DOCUMENT_ROOT']."/upload";
            $image = \think\Image::open($_SERVER['DOCUMENT_ROOT'].$daili_info['ysz']);
            //生成头像缩略图
            $my_thumb = time().$daili_id.".png";
            $image->thumb(142,182,\think\Image::THUMB_CENTER)->save($root_dir.'/'.$my_thumb);
            
            $image_mb = \think\Image::open($root_dir.'/CardShow.jpg');
            $my_ls_img = time().$daili_id."ls.png";//临时图片
            $image_mb->water($root_dir.'/'.$my_thumb,array(550,485))->save($root_dir.'/'.$my_ls_img);
            $image_mb->text($daili_info['dlname'],$root_dir.'/simhei.ttf',20,'#000000',array(180,317))->save($root_dir.'/'.$my_ls_img);
            
            $image_mb = \think\Image::open($root_dir.'/'.$my_ls_img);
            $image_mb->text($daili_info['dl_phone'],$root_dir.'/simhei.ttf',20,'#000000',array(210,473))->save($root_dir.'/'.$my_ls_img);
            
            $image_mb = \think\Image::open($root_dir.'/'.$my_ls_img);
            $image_mb->text($daili_info['dl_weixin'],$root_dir.'/simhei.ttf',20,'#000000',array(200,530))->save($root_dir.'/'.$my_ls_img);
            
            $image_mb = \think\Image::open($root_dir.'/'.$my_ls_img);
            $province_text = Db::name('city')->where("code = '{$daili_info['province']}' and p_code = 0")->value('name');
            $city_text = Db::name('city')->where("code = '{$daili_info['city']}'  and p_code != 0")->value('name');
            $area_text = Db::name('city')->where("code = '{$daili_info['area']}'")->value('name');
            $image_mb->text($province_text.$city_text.$area_text,$root_dir.'/simhei.ttf',20,'#000000',array(210,579))->save($root_dir.'/'.$my_ls_img);
            
            $image_mb = \think\Image::open($root_dir.'/'.$my_ls_img);
            $sfzh = strlen($daili_info['sfzh'])==15?substr_replace($daili_info['sfzh'],"****",8,4):(strlen($daili_info['sfzh'])==18?substr_replace($daili_info['sfzh'],"****",10,4):"");
            $image_mb->text($sfzh,$root_dir.'/simhei.ttf',20,'#000000',array(200,638))->save($root_dir.'/'.$my_ls_img);
            
            $image_mb = \think\Image::open($root_dir.'/'.$my_ls_img);
            $my_sqs_img = time().$daili_id."sqs.png";
            $image_mb->text($daili_info['sqh'],$root_dir.'/simhei.ttf',20,'#000000',array(270,713))->save($root_dir.'/sqs/'.$my_sqs_img);
            //删除临时图片
            unlink($root_dir.'/'.$my_thumb);
            unlink($root_dir.'/'.$my_ls_img);
            Db::name('daili')->where("id = '{$daili_id}'")->update(['sqs_path' => '/upload/sqs/'.$my_sqs_img]);
        }
        $daili_info = Db::name('daili')->where("sqh != '' and id = '{$daili_id}'")->find();
        $this->assign("daili_info",$daili_info); 
        return $this->fetch();
    }
    
    /**
     * 代理邀请
     */
    public function shareAgent(){
        $this->isLogin();
        $daili_id = session('index_daili.id');
        $daili_info = Db::name('daili')->where("sqh != '' and id = '{$daili_id}'")->find();
        $daili_info['dailijb'] = Db::name('dldj')->where("id = '{$daili_info['lddj_id']}'")->value('levelname');
        if($daili_info['lddj_id'] == 1){
            $daili_info['ktjdj'] =  Db::name('dldj')->where("id < 3")->select();
        }else if($daili_info['lddj_id'] == 2){
            $daili_info['ktjdj'] =  Db::name('dldj')->where("id < 4")->select();
        }else if($daili_info['lddj_id'] == 3 || $daili_info['lddj_id'] == 4){
            $daili_info['ktjdj'] =  Db::name('dldj')->where("id < 5")->select();
        }
        $this->assign("daili_info",$daili_info);
        return $this->fetch();
    }
    
    /**
     * 代理分享海报页面
     */
    public function shareHaibao(){
        //$this->isLogin();
        $dl_level = unlock_url(input('get.dl_level'));
        $pid = unlock_url(input('get.pid'));
        $start_time = unlock_url(input('get.start_time'));
        $end_time = $start_time+10*60;
        $jssdk = new Jssdk("wxd232643ac5db648b", "160deec51168bd49413a6ec58fa3804b");
        $signPackage = $jssdk->GetSignPackage();
        
        $daili_id = session('index_daili.id');//当前代理ID
        $show_status = 0;//默认显示授权书
        $gzxx = 1;
        if(isset($daili_id) && !empty($daili_id)){
            if($daili_id == $pid){
                //显示授权书
                $show_status = 0;
            }else{
                //跳转个人中心
                $this->redirect(url("user/index"),302);
            }
        }else{
            //显示注册说明
            $show_status = 1; 
            if(isset($_SESSION['sq_openid']) && !empty($_SESSION['sq_openid'])){
                $user_openid = $_SESSION['sq_openid'];
                $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd232643ac5db648b&secret=160deec51168bd49413a6ec58fa3804b";
                $access_msg = json_decode(file_get_contents($access_token));
                $token = $access_msg->access_token;
                $subscribe_msg = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$user_openid";
                $subscribe = json_decode(file_get_contents($subscribe_msg));
                $gzxx = $subscribe->subscribe; 
            }else{
                $wchat = new \wechat\WechatOauth();
                $code = request()->param('code',"");
                $user = $wchat->getUserAccessUserInfo($code); 
                $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd232643ac5db648b&secret=160deec51168bd49413a6ec58fa3804b";
                $access_msg = json_decode(file_get_contents($access_token));
                $token = $access_msg->access_token; 
                $subscribe_msg = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$token&openid=$user[openid]";
                $subscribe = json_decode(file_get_contents($subscribe_msg)); 
                $_SESSION['sq_openid'] = $subscribe->openid;
                $gzxx = $subscribe->subscribe; 
            } 
            $this->assign("sq_openid",$_SESSION['sq_openid']);
        }
        
        $my_info = Db::name('daili')->where("id = '{$pid}'")->find();
        
        $this->assign("dl_level",$dl_level);
        $this->assign("pid",$pid);
        $this->assign("my_info",$my_info);
        $this->assign("djsss",$end_time-time());
        $this->assign("start_time",$start_time);
        $this->assign("gzxx",$gzxx);
        
        $this->assign("signPackage",$signPackage);
        $this->assign("show_status",$show_status);
        return $this->fetch();
    }
    
    /**
     * 代理注册 
     */
    public function agentReg(){
        if($this->request->isPost()){
            $data = $this->request->post(); 
            if($data['dlname'] == ''){
                return $this->error("请填写姓名");
            }
            if($data['dl_weixin'] == ''){
                return $this->error("请填写微信");
            }
            if($data['dl_phone'] == ''){
                return $this->error("请填写手机号");
            }
            //判断手机号是否已存在
            if(Db::name("daili")->where("dl_phone = '{$data['dl_phone']}'")->count() > 0){
                return $this->error("该手机号已经注册过了");
            }
            if($data['sfzh'] == ''){
                return $this->error("请填写身份证");
            }
            if($data['province'] == 0 || $data['city'] == 0 || $data['area'] == 0){
                return $this->error("请选择授权地区");
            }
            if($data['shdz'] == ''){
                return $this->error("请填写收货地址");
            }
            if($data['qianzy'] == ''){
                return $this->error("请填写前职业");
            }
            if($data['sex'] == ''){
                return $this->error("请选择性别");
            }
            if($data['hyzk'] == ''){
                return $this->error("请选择婚姻状况");
            } 
            if($data['sfzzm'] == ''){
                return $this->error("请上传身份证正面照");
            }
            if($data['sfzfm'] == ''){
                return $this->error("请上传身份证反面照");
            }
            if($data['scsfz'] == ''){
                return $this->error("请上传本人手持身份证");
            }
            if($data['ysz'] == ''){
                return $this->error("请上传艺术照");
            }
            if($data['zzpz'] == ''){
                return $this->error("请上传转账凭证");
            } 
            unset($data['checkbox']);
            $levelname = $data['levelname'];
            unset($data['levelname']);
            $data['ppid'] = Db::name("daili")->where("id = '{$data['pid']}'")->value("pid");
            //手机号后六位默认密码
            $data['password'] = md5(substr($data['dl_phone'],-6));
            $data['create_time'] = time();
            $data['xtgs'] = Db::name("dldj")->where("id = '{$data['lddj_id']}'")->value("xtgs");//系统个数
            if (!Db::name('daili')->insert($data)) {
                return $this->error('注册失败');
            }
            //注册成功，代理系统个数减一（初始代理不减）
            //if($data['pid'] != 1){
            //    Db::name('daili')->where("id = '{$data['pid']}'")->setDec('xtgs');
            //} 
            $datas = array(
                'first' => array('value'=>urlencode("注册信息已经提交成功，请等待系统审核！")),
                'keyword1' => array('value' => urlencode($levelname)),
                'keyword2' => array('value' => urlencode("待审核")),
                'remark' => array('value' => "点击登录系统"),
            );
            $this->template_reserve($data['openid'], "http://daili.huyingbaoxt.com/", $datas);
            
            
            return $this->success("注册信息已经提交成功，请等待系统审核。登录账户：".$data['dl_phone'].";密码：".substr($data['dl_phone'],-6));
        }else{
            $dl_id = unlock_url(input('get.dl_id'));
            $pid = unlock_url(input('get.pid'));
            $start_time = unlock_url(input('get.start_time'));
            $end_time = $start_time+10*60;
            $openid = input('get.openid');
            
            $province = Db::name('city')->where("p_code = 0")->select();
            $city = Db::name('city')->where("code = 110000 and p_code = 110000")->select();
            $area = Db::name('city')->where("p_code = 110000")->select();
            
            $fjdl_info = Db::name('daili')->where("id = '{$pid}'")->find();
            $dldj_info = Db::name('dldj')->where("id = '{$dl_id}'")->find();
            
            $this->assign("province",$province);
            $this->assign("city",$city);
            $this->assign("area",$area);
            $this->assign("djsss",$end_time-time());
            $this->assign("fjdl_info",$fjdl_info);
            $this->assign("dldj_info",$dldj_info);
            $this->assign("openid",$openid);
            return $this->fetch();
        } 
    }
    
    /**
     * 预约模板消息
     * @param str $touser
     * @param str $dhjp
     * @param str $kjsj
     * @param str $turl
     * @return unknown
     */
    public function template_reserve($touser,$turl,$data){
        $json_token = $this->http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd232643ac5db648b&secret=160deec51168bd49413a6ec58fa3804b");
        
        $access_token = json_decode($json_token,true);
        //获得access_token 
        $maccess_token = $access_token['access_token'];
        $template=array(
            'touser' => $touser,
            'template_id' => "nCPwdrI3xDvB80F2TeSNdIhIvugsZz8QkWAFEki-9JM",
            'url' => $turl,
            'topcolor' => "#7B68EE",
            'data'=> $data
        );
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$maccess_token;
        $res = $this->http_request($url,urldecode($json_template));
        return $res;
    }
    
    function http_request($url,$data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
    
    /**
     * 下级代理
     */
    public function myXiaji(){
        $this->isLogin();
        $daili_id = session('index_daili.id');
        $xj_list = Db::name('daili')->where("pid = '{$daili_id}'")->select();
        foreach ($xj_list as $key => $val){
            $xj_list[$key]['dailijb'] = Db::name('dldj')->where("id = '{$val['lddj_id']}'")->value('levelname');
        }
        
        $this->assign("xj_list",$xj_list);
        return $this->fetch();
    }
    
    /**
     * 佣金记录
     */
    public function myYongjin(){
        $this->isLogin(); 
        return $this->fetch();
    }
    
    /**
     * 个人信息
     */
    public function userInfo(){
        if($this->request->isPost()){
            $data = $this->request->post(); 
            if($data['dl_weixin'] == ''){
                return $this->error("请填写微信");
            }
            if($data['dl_phone'] == ''){
                return $this->error("请填写手机号");
            }
            $daili_id = session('index_daili.id');
            $user_info = Db::name('daili')->where("id = '{$daili_id}'")->find();
            //判断手机号是否已存在
            if($user_info['dl_phone'] != $data['dl_phone']){
                if(Db::name("daili")->where("dl_phone = '{$data['dl_phone']}'")->count() > 0){
                    return $this->error("该手机号已经注册过了");
                } 
            }
            
            if($data['shdz'] == ''){
                return $this->error("请填写收货地址");
            }
            if($data['qianzy'] == ''){
                return $this->error("请填写前职业");
            }
            if($data['sex'] == ''){
                return $this->error("请选择性别");
            }
            if($data['hyzk'] == ''){
                return $this->error("请选择婚姻状况");
            }
            if (!Db::name('daili')->update($data)) {
                return $this->error('更新失败');
            }
            return $this->success('更新成功');
        }else{
            $daili_id = session('index_daili.id');
            $user_info = Db::name('daili')->where("id = '{$daili_id}'")->find();
            
            $user_info['levelname'] = Db::name('dldj')->where("id = '{$user_info['lddj_id']}'")->value('levelname');
            $user_info['province_text'] = Db::name('city')->where("code = '{$user_info['province']}' and p_code = 0")->value('name');
            $user_info['city_text'] = Db::name('city')->where("code = '{$user_info['city']}'  and p_code != 0")->value('name');
            $user_info['area_text'] = Db::name('city')->where("code = '{$user_info['area']}'")->value('name');
            
            if($user_info['wxtx'] == ''){
                $user_info['wxtx'] = $user_info['ysz'];
            }
            
            $this->assign("user_info",$user_info);
            return $this->fetch();
        }
    }
    
    /**
     * 绑定微信
     */
    public function bdwx(){
        $this->isLogin();
        $wchat = new \wechat\WechatOauth(); 
        $code = request()->param('code',"");
        $user = $wchat->getUserAccessUserInfo($code); 
        $data['openid'] = $user['openid'];
        $data['wxnc'] = $user['nickname'];
        $data['wxtx'] = $user['headimgurl'];
        $daili_id = session('index_daili.id');
        $daili_info = Db::name('daili')->where("id = '{$daili_id}'")->find();
        if($daili_info['openid'] != ''){
            $this->success("您已经绑定过了！",url('user/index'));
        }
        $res = Db::name('daili')->where("id = '{$daili_id}'")->update($data);
        if($res){
            $this->success("绑定成功！",url('user/index'));
        }else{
            $this->error("绑定失败！",url('user/index'));
        }
    }
    
    /**
     * 修改密码
     */
    public function editPwd(){
        $this->isLogin();
        if($this->request->isPost()){
            $data = $this->request->post();
            $daili_id = session('index_daili.id');
            $daili_info = Db::name('daili')->where("id = '{$daili_id}'")->find();
            if($daili_info['password'] == md5($data['oldpwd'])){
                if($data['newpwd'] != $data['qrpwd']){
                    $this->error("两次密码不一样！");
                }
                $res = Db::name('daili')->where("id = '{$daili_id}'")->update(['password' => md5($data['newpwd'])]);
                if($res){
                    session('index_daili', NULL);
                    $this->success("修改成功！");
                }else{
                    $this->error("修改失败！");
                }
            }else{
                $this->error("原始密码错误！");
            }
        }else{
            return $this->fetch();
        }
    }
    
    /**
     * 首充返利-Ajax
     */
    public function scflAjax(){
        $p = $this->request->param('p');
        $daili_id = session('index_daili.id');
        $list = Db::name('czfljl')->where("dl_id = '{$daili_id}'")->page($p,10)->select();
        foreach ($list as $key => $val){
            $list[$key]['daili'] = Db::name("daili")->where("id = '{$val['czjl_id']}'")->find();
        }
        return $list;
    }
    
    /**
     * 采购返利-Ajax
     */
    public function cgflAjax(){
        $p = $this->request->param('p');
        $daili_id = session('index_daili.id');
        $list = Db::name('cgfl')->where("dl_id = '{$daili_id}'")->page($p,10)->select();
        foreach ($list as $key => $val){
            $list[$key]['cgjl'] = $cgjl = Db::name("cgjl")->where("id = '{$val['cgjl_id']}'")->find();
            $list[$key]['daili'] = Db::name("daili")->where("id = '{$cgjl['dl_id']}'")->find();
        }
        return $list;
    }
    
    /**
     * 提现
     */
    public function tixian(){
        $this->isLogin();
        if($this->request->isPost()){
            $data = $this->request->post();
            $daili_id = session('index_daili.id');
            $daili_info = Db::name('daili')->where("id = '{$daili_id}'")->find();
            
            if($data['txje'] == '' || $data['txje'] == 0){
                return $this->error('提现金额不能为0！');
            }
            if($data['txje'] > $daili_info['yongjin']){
                return $this->error('提现金额超限！');
            }
            
            
            $data['sqsj'] = time();
            $data['dl_id'] = $daili_id; 
            if (Db::name("tixian")->insert($data)) { 
                Db::name('daili')->where("id = '{$daili_id}'")->setDec('yongjin',$data['txje']);
                return $this->success('申请成功，等待系统审核！');
            }else{
                return $this->error('申请失败');
            } 
        }else{
            $daili_id = session('index_daili.id');
            $daili_info = Db::name('daili')->where("id = '{$daili_id}'")->find();
            $this->assign("daili_info",$daili_info);
            return $this->fetch();
        } 
    }
    
    /**
     * 退出登录
     */
    public function outLogin(){
        session('index_daili', NULL);
        $this->success("退出成功！",url('index/index'));
    }
    
    /**
     * 上传图片
     */
    public function uploadImg(){
        $data = $this->request->post();
        $base64_img = trim($data['formFile']);
        $up_dir = './upload/daili_reg/';//存放在当前目录的upload文件夹下
        
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777);
        }
        
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            $type = $result[2];
            if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $new_file = $up_dir.date('YmdHis_').'.'.$type;
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    $img_path = str_replace('./', '/', $new_file);
                    return array(
                        'status' => 1,
                        'img_path' => $img_path
                    );
                }else{
                    return array(
                        'status' => 0,
                        'img_path' => ''
                    );
                }
            }else{
                return array(
                    'status' => 0,
                    'img_path' => ''
                );
                //echo '图片上传类型错误';
            }
            
        }else{
            //文件错误
            echo '文件错误';
        }
    }
    
    /**
     * 生成加密参数
     */
    public function lockUrl(){
        $data = $this->request->post();
        return lock_url($data['parame']);
    }
    
    /**
     * 获取城市
     */
    public function getCity(){
        $data = $this->request->post();
        if($data['province'] == 110000 || $data['province'] == 500000 || $data['province'] == 310000 || $data['province'] == 120000){
            return Db::name('city')->where("code = '{$data['province']}' and p_code = '{$data['province']}'")->select();
        }else{
            return Db::name('city')->where("p_code = '{$data['province']}'")->select();
        } 
    }
    
    /**
     * 获取地区
     */
    public function getArea(){
        $data = $this->request->post();
        return Db::name('city')->where("p_code = '{$data['city']}' and code != '{$data['city']}'")->select();
    }
}
